use actix_web::{HttpResponse};
use serde::{ser};
use lucky::json::{JsonError, JsonOK, JsonResult};

/// 定义PgPool
pub type Pool = actix_web::web::Data<sqlx::PgPool>;

#[macro_export]
macro_rules! get {
    ($path: expr, $fun: expr) => ({
        actix_web::web::resource($path).route(actix_web::web::get().to($fun))
    })
}

#[macro_export]
macro_rules! post {
    ($path: expr, $fun: expr) => ({
        actix_web::web::resource($path).route(actix_web::web::post().to($fun))
    })
}

pub struct Response;

impl Response {

    /// response 200
    #[allow(dead_code)]
    pub fn ok() -> HttpResponse {
        HttpResponse::Ok().json(JsonOK{code: 0})
    }

    /// 拒絕訪問
    #[allow(dead_code)]
    pub fn deny() -> HttpResponse {
        HttpResponse::Ok().body("deny")
    }

    /// response error message
    #[allow(dead_code)]
    pub fn error<'a>(message: &'a str) -> HttpResponse {
        let err = JsonError {
            code: 500,
            message,
        };
        let result = encrypt_struct!(JsonError :: &err);
        HttpResponse::Ok().content_type("application/json").body(result)
    }

    /// 直接输出json
    #[allow(dead_code)]
    pub fn encrypt_data<T: ser::Serialize>(data: &T) -> HttpResponse {
        let result = encrypt_struct!(T :: &data);
        HttpResponse::Ok().content_type("application/json").body(result)
    }

    /// response complicated data
    #[allow(dead_code)]
    pub fn result<T: ser::Serialize>(result: &T) -> HttpResponse {
        let res = JsonResult {
            code: 0,
            result,
        };
        HttpResponse::Ok().json(res)
    }

    // 页面重定向
    //#[allow(dead_code)]
    //pub fn redirect(url: &str) -> HttpResponse {
    //    HttpResponse::Found().header(header::LOCATION, url).finish()
    //}
}

pub mod models;
